<?php


namespace app\common\business;


use think\Exception;
use app\common\model\mysql\GoodsSku as GoodsSkuModel;
class GoodsSku extends BusBase
{
    public $model = NULL;
    public function __construct()
    {
        $this->model = new GoodsSkuModel();
    }

    /**
     * 批量新增
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function saveAll($data){
        if(!$data['skus']) {
            return false;
        }
        foreach($data['skus'] as $value){
            $insertData[] = [
                "goods_id" => $data['goods_id'],
                "specs_value_ids" => $value['propvalnames']['propvalids'],
                "price" => $value['propvalnames']['skuSellPrice'],
                "cost_price" => $value['propvalnames']['skuMarketPrice'],
                "stock" => $value['propvalnames']['skuStock'],
            ];
        }
        // number_format round
        try {
            $result = $this->model->saveAll($insertData);
            return $result->toArray();
        } catch(Exception $e){
            // 记录日志
            return false;
        }
    }

    public function goods() {
    	return $this->hasOne(Goods::class, "id","goods_id");
	}

    public function getNormalSkuAndGoods($id){
        try {
            $result = $this->model->with("goods")->find($id);// withJoin是join查询
        } catch(Exception $e){
            return [];
        }
        if(!$result){
            return [];// 因为不存在返回null
        }
        $result = $result->toArray();
        if($result['status'] != config("status.mysql.table_normal")){
            return [];
        }
        return $result;
    }

    public function getSkusByGoodsId($goodsId){
        if(!$goodsId){
            return [];
        }
        try {
            $skus = $this->model->getNormalByGoodsId($goodsId);
        } catch(Exception $e){
            return [];
        }
        return $skus->toArray();
    }
    public function getNormalInIds($ids){
        try {
            $result = $this->model->getNormalInIds($ids);
        }catch(Exception $e){
            return [];
        }
        return $result->toArray();
    }


    public function updateStock($data){
        // 实际上 此处循环存在性能瓶颈
        // 思路：10 sku_id stock 前[1=>10, 2=>4]  减量[2, 1]  后[1=>9, 2=>3]
        // 批量更新方式去处理
        foreach($data as $value){
            $this->model->decStock($value['id'], $value['num']);
        }
        return true;
    }
}
